import React, { useState, useEffect } from 'react';
import s from './style.module.css';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import HostIndex from './hostIndex';
import WebIndex from './webIndex';
import { turnToUrlparam, GetQueryString } from '../../../helpers/getUrlParams';
import fetchFer from 'API/fetch';
import Loading from '@knownsec/react-component/dist/Loading';

function JobDetail({
	match: {
		params: { assetType },
	},
	location,
	history,
}) {
	const [loading, setLoading] = useState(false);
	const [row, setRow] = useState();
	const getRow = async () => {
		setLoading(true);
		const jid = GetQueryString(location.search, 'jid');
		const target_url = GetQueryString(location.search, 'url');
		const task_id = GetQueryString(location.search, 'task_id');
		const params = turnToUrlparam({
			asset_type: assetType,
			target_url,
			task_id,
		});
		const urlType = '/api/v2/asset/asset_list';
		const res = await fetchFer(`${urlType}?${params}`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(() => {
			return [];
		});
		const results = res.data?.results;
		if (results[0]) {
			const screening = results.filter(item => {
				return item.job_id === jid;
			});
			if (screening[0]) {
				setRow(screening[0]);
			} else {
				// jid不同
				history.replace(`/asset-manage/manage/${assetType}`);
			}
		} else {
			// 资产地址不存在
			history.replace(`/asset-manage/manage/${assetType}`);
		}
		setLoading(false);
	};
	useEffect(() => {
		getRow();
	}, []);
	return (
		<div className={s.taskMain}>
			<Breadcrumb>
				<Item key="asset-manage" disabled>
					资产管理
				</Item>
				<Item key={`manage/${assetType}`}>
					{assetType === 'web' ? 'Web' : '主机'}资产
				</Item>
				<Item key="">详情</Item>
			</Breadcrumb>
			<Loading show={loading} label="" />
			{assetType === 'web' && row && (
				<WebIndex
					row={row}
					assetType={assetType}
					location={location}
					history={history}
				/>
			)}
			{assetType === 'host' && row && (
				<HostIndex row={row} assetType={assetType} />
			)}
		</div>
	);
}
JobDetail.propTypes = {
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
	location: PropTypes.any,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
		replace: PropTypes.func.isRequired,
	}).isRequired,
};
export default withRouter(JobDetail);
